<!--分页器-->
<script setup>
import JumpPage from "@/components/common/JumpPage.vue";
import {ArrowLeftBold, ArrowRightBold, DArrowLeft, DArrowRight,} from "@element-plus/icons-vue";
import {ref, toRefs, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {DomUtils} from "@/assets/js/DomUtils";

const props = defineProps({data: Object})
const data = toRefs(props).data

const route = useRoute()
const router = useRouter()

// 当前页
const page = ref();
// 每页数量
const size = ref();
// 总条数
const total = ref();
// 总页数
const totalPage = ref();
// 分页器页码
const pages = ref();

// 应用数据
const applyData = (data) => {
  if (!data.size) {
    return
  }
  page.value = Number(data.page || route.query.page || 1)
  size.value = data.size
  total.value = data.total
  if (data.totalPage) {
    totalPage.value = data.totalPage
  } else {
    totalPage.value = Math.floor(data.total / data.size) + (data.total % data.size > 0 ? 1 : 0)
  }
  // 前后长度
  const length = 3;
  // 分页器起始页数
  const minPage = Math.max(1, page.value - length)
  const maxPage = Math.min(totalPage.value, Math.max(page.value + length, 6))
  const arr = []
  for (let i = minPage; i < maxPage + 1; i++) {
    arr.push(i)
  }
  pages.value = arr
}
// 跳转到指定页数
const goPage = (page) => {
  DomUtils.scrollTop();
  router.push({query: {...route.query, page}})
}

data.value && applyData(data.value)

watch(data, (nv) => {
  applyData(nv)
})

defineEmits(["refresh"])

</script>

<template>
  <div v-if="totalPage>1" style="display: inline-block">
    <el-button-group size="small" type="primary">
      <!--上一页-->
      <el-button v-if="pages && !pages.includes(1)" :icon="DArrowLeft" @click="goPage(1)"/>
      <el-button v-if="page!==1" :icon="ArrowLeftBold" @click="goPage(page-1)"/>
      <el-button v-for="i in pages" :type="page===i?'warning':'success'" @click="page===i?$emit('refresh'):goPage(i)">{{ i }}</el-button>
      <!--下一页-->
      <el-button v-if="page<totalPage" :icon="ArrowRightBold" @click="goPage(page+1)"/>
      <el-button v-if="pages&&pages[pages.length-1]<totalPage" :icon="DArrowRight" @click="goPage(totalPage)"/>

      <jump-page v-if="totalPage &&totalPage>1" :id="Number(route.params.id)" :name="route.name.toString()" :total-page="totalPage">
        <el-button>
          跳页
        </el-button>
      </jump-page>
    </el-button-group>
    <span>共 {{ total }} 条, {{ totalPage }} 页</span>
  </div>
</template>

<style scoped>
.el-button {
  padding: 5px
}
</style>